package curlutil

import (
	"errors"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
)

// HttpCurl   curl 请求
func HttpCurl(method, u string, data io.Reader, header map[string]string) (*http.Response, error) {
	client := http.Client{}
	var (
		req *http.Request
		err error
	)
	switch strings.ToLower(method) {
	case "post", "put", "delete", "head":
		req, err = http.NewRequest(method, u, data)
	case "get":
		if data != nil {
			p, err := ioutil.ReadAll(data)
			if err != nil {
				log.Println("读取数据失败", err)
				return nil, err
			}
			path, err := url.ParseQuery(string(p))
			if err != nil {
				log.Println("数据转换url path失败", err)

				return nil, err
			}
			if strings.Contains(u, "?") {
				u += "&" + path.Encode()
			} else {
				u += "?" + path.Encode()
			}
		}
		req, err = http.NewRequest("GET", u, nil)
	default:
		return nil, errors.New("不支持该请求方式")
	}
	if err != nil {
		log.Println("http newRequest失败", err)
		return nil, err
	}
	if header != nil {
		for k, v := range header {
			log.Println(k, v)
			req.Header.Set(k, v)
		}
	}
	return client.Do(req)
}
